﻿using System;
using ZFine.Application.Gas;
using ZFine.Application.SystemManage;
using ZFine.Code;
using ZFine.Domain.Entity.Gas;
using ZFine.Domain.Entity.SystemManage;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using ZFine.Web.Services;
using ZFine.Domain;
using System.Collections;

namespace ZFine.Web.Areas.Gas.Controllers
{
    public class ApplyController : ControllerBase
    {
        private ApplyApp applyApp = new ApplyApp();
        private SchoolApp schoolApp = new SchoolApp();
        private ClassApp classApp = new ClassApp();
        private ItemsDetailApp itemsDetailApp = new ItemsDetailApp();
        private EduConfigApp eduConfigApp = new EduConfigApp();
        private RoleApp roleApp = new RoleApp();

        [HttpGet]
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Form()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Details()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult Update()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult Upload()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult SchoolOperateIndex()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult SchoolReviewForm()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult SchoolQueryIndex()
        {
            return View();
        }
        
        [HandlerAuthorize(ignore: false)]
        public ActionResult DataShareForm()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(ignore: false)]
        public ActionResult RegisterForm()
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            string UserCode = "";
            if (LoginInfo != null)
            {
                UserCode = LoginInfo.UserCode;
            }
            ViewBag.Account = UserCode;
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult ApplyIndex()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult OStatusUpdate()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult AdmitIndex()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult ReportIndex()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult ReportEducationIndex()
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            RoleEntity roleEntity = roleApp.GetForm(LoginInfo.RoleId);
            ViewBag.switchDiv = "block";
            if (null != roleEntity)
            {
                if ("1" == roleEntity.F_Type)
                {
                    ViewBag.switchDiv = "block";
                }
                else
                {
                    ViewBag.switchDiv = "none";
                }
            }
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult ReportDefaultIndex()
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            RoleEntity roleEntity = roleApp.GetForm(LoginInfo.RoleId);
            ViewBag.switchDiv = "block";
            if (null != roleEntity)
            {
                if ("3" == roleEntity.F_Type)
                {
                    ViewBag.switchDiv = "none";
                }
                else
                {
                    ViewBag.switchDiv = "block";
                }
            }
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, ApplyEntity in_apply)
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            List<ApplyEntity> l_apply = applyApp.GetList(pagination, LoginInfo.UserCode);
            //取得当前的配置表里面的提交状态
            List<EduConfigEntity> registerList = eduConfigApp.GetIQueryable("submit_status", "3").ToList();
            string submitStatus = "0";
            if (null != registerList && 0 != registerList.Count)
            {
                submitStatus = registerList[0].ConfigValue;
            }
            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = l_apply,//分页的数据
                total = pagination.total,//页数
                TotalCount = l_apply.ToArray().Length,
                submitStatus = submitStatus,
            };
            return Content(data.ToJson());
        }

        //查询属于当前学校的数据
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJsonBySchool(Pagination pagination, ApplyEntity in_apply, string RName, string IDNumber, string OStatus, string HouseFlag, string HouseClass,string classValue)
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            // 根据学校账号查询学校表的主键ID
            List<SchoolEntity> l_school = schoolApp.GetListByAccount(LoginInfo.UserCode);
            List<ApplyEntity> l_apply = new List<ApplyEntity>();
            if (l_school.Count() > 0)
            {
                l_apply = applyApp.GetListBySchool(pagination, l_school.ToArray()[0].F_Id, RName, IDNumber, OStatus, HouseFlag, HouseClass, classValue);
            }
            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = l_apply,//分页的数据
                total = pagination.total,//页数
                TotalCount = l_apply.ToArray().Length,
            };
            return Content(data.ToJson());
        }

        //教育局查询方法
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJsonByEdu(Pagination pagination, string schoolId, string RName, string IDNumber, string OStatus, string txtHouseFlag, string admit, string HouseClass, string IsPwdKeyApply,string classValue)
        {
            List<ApplyEntity> l_apply = applyApp.GetListByEdu(pagination, schoolId, RName, IDNumber, OStatus, txtHouseFlag, admit, HouseClass, IsPwdKeyApply, classValue);
            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = l_apply,//分页的数据
                total = pagination.total,//页数
                TotalCount = l_apply.ToArray().Length,
            };
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult CheckData()
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            List<ApplyEntity> l_apply = applyApp.GetIQueryable(LoginInfo.UserCode).ToList();
            var data = new
            {
                TotalCount = l_apply.ToArray().Length,
            };
            return Content(data.ToJson());
        }
        //修改页数据
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJsonForUpdate(string keyValue)
        {
            ApplyEntity data = applyApp.GetForm(keyValue);
            return Content(data.ToJson());
        }
        //详情页数据
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            ApplyEntity data = applyApp.GetForm(keyValue);
            return Content(data.ToJson());
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitForm(ApplyEntity applyEntity, string txtIDNumber)
        {
            //一个学生只存在一条申请记录（以身份证号进行检索）
            ApplyEntity result = applyApp.GetFormByIDNumber(txtIDNumber);
            if (null != result)
            {
                Dictionary<string, string> data = new Dictionary<string, string>();
                data.Add("message", "此身份证号已经申请");
                return Content(data.ToJson());
            }
            //根据是否密钥申请,判读是否接入共享平台的第三方验证
            if("1" == applyEntity.HouseFlag || "2" == applyEntity.HouseFlag)
            {
                try
                {
                    if (!isPwdKeyApply(applyEntity) && (!checkHouseInfo(applyEntity))) //不是密钥申请的情况下，需要验证
                    {
                        Dictionary<string, string> data = new Dictionary<string, string>();
                        data.Add("message", "房屋信息验证失败。");
                        return Content(data.ToJson());
                    }
                }catch(Exception e)
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("message", "共享平台数据返回异常，请联系管理员");
                    return Content(data.ToJson());
                }
            }
            else
            {
                applyEntity.isPwdKeyApply = "0";
            }
            applyEntity.RegTime = DateTime.Now;
            //如果改为未提交，更新时间设置为最小时间
            if ("0" == applyEntity.OStatus || "1" == applyEntity.OStatus)
            {
                applyEntity.LastUpdateTime = PubClass.MinDate();
            }
            //家长提交时更新最终提交时间
            if ("2" == applyEntity.OStatus)
            {
                applyEntity.LastUpdateTime = DateTime.Now;
                //重新更新申请序号
                string applyNumber = updateApplyNumber(applyEntity,"");
                applyEntity.ApplyNumber = applyNumber;
            }
            // 根据住房类别清空div区域字段
            clearValueByHouseFlag(applyEntity);
            applyApp.SubmitForm(applyEntity, "");
            return Success("操作成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateForm(ApplyEntity applyEntity, string keyValue)
        {
            //根据是否密钥申请,判读是否接入共享平台的第三方验证
            if ("1" == applyEntity.HouseFlag || "2" == applyEntity.HouseFlag)
            {
                try
                {
                    if (!isPwdKeyApply(applyEntity) && (!checkHouseInfo(applyEntity))) //不是密钥申请的情况下，需要验证
                    {
                        Dictionary<string, string> data = new Dictionary<string, string>();
                        data.Add("message", "房屋信息验证失败。");
                        return Content(data.ToJson());
                    }
                }
                catch (Exception e)
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("message", "共享平台数据返回异常，请联系管理员");
                    return Content(data.ToJson());
                }
            }
            else
            {
                applyEntity.isPwdKeyApply = "0";
            }
            //如果改为未提交，更新时间设置为最小时间
            if ("0" == applyEntity.OStatus || "1" == applyEntity.OStatus)
            {
                applyEntity.LastUpdateTime = PubClass.MinDate();
            }
            //家长提交时更新最终提交时间
            if ("2" == applyEntity.OStatus)
            {
                applyEntity.LastUpdateTime = DateTime.Now;
                //重新更新申请序号
                string applyNumber = updateApplyNumber(applyEntity, keyValue);
                applyEntity.ApplyNumber = applyNumber;
            }
            // 根据住房类别清空div区域字段
            clearValueByHouseFlag(applyEntity);
            //发送短信通知
            this.sendSMS(applyEntity);
            //更新数据
            applyApp.SubmitForm(applyEntity, keyValue);
            return Success("操作成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateFormBySchoolAndEdu(ApplyEntity applyEntity, string keyValue,string schoolUpd)
        {
            if("1"  == schoolUpd &&  "4" == applyEntity.OStatus)
            {
                string schoolId = applyEntity.SchoolId;
                string classValue = applyEntity.Class;
                //取得当前学校年级得可转学总数
                int totalAmount = classApp.GetClassFreeTotalAmount(schoolId, classValue);
                //已经通过预录取和录取的总数
                int passAmount = applyApp.GetCount(schoolId, classValue);
                //如果已经通过预录取和录取的总数超取得当前学校年级得可转学总数,则不再可以预录取
                if (passAmount >= totalAmount)
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("message", "当前学校录取名额已满。");
                    return Content(data.ToJson());
                }
            }
            //初审不过的情况下，取消当前排位
            if("3" == applyEntity.OStatus)
            {
                applyEntity.LastUpdateTime = PubClass.MinDate();
                applyEntity.ApplyNumber = "";
                //重新更新申请序号
                updateApplyNumber(applyEntity, keyValue);
            }
            //根据是否密钥申请,判读是否接入共享平台的第三方验证
            if ("1" == applyEntity.HouseFlag || "2" == applyEntity.HouseFlag)
            {
                try
                {
                    if (!isPwdKeyApply(applyEntity) && (!checkHouseInfo(applyEntity))) //不是密钥申请的情况下，需要验证
                    {
                        Dictionary<string, string> data = new Dictionary<string, string>();
                        data.Add("message", "房屋信息验证失败。");
                        return Content(data.ToJson());
                    }
                }
                catch (Exception e)
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("message", "共享平台数据返回异常，请联系管理员");
                    return Content(data.ToJson());
                }
            }
            else
            {
                applyEntity.isPwdKeyApply = "0";
            }
            // 根据住房类别清空div区域字段
            clearValueByHouseFlag(applyEntity);
            //发送短信通知
            this.sendSMS(applyEntity);
            //更新数据
            applyApp.SubmitForm(applyEntity, keyValue);
            return Success("操作成功。");
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateOStatusByEdu(ApplyEntity applyEntity, string keyValue)
        {
            ApplyEntity data = applyApp.GetForm(keyValue);
            data.OStatus = applyEntity.OStatus;
            // 根据住房类别清空div区域字段
            clearValueByHouseFlag(data);
            //发送短信通知
            this.sendSMS(data);
            //如果改为未提交，更新时间设置为最小时间
            if ("0" == data.OStatus || "1" == data.OStatus)
            {
                data.LastUpdateTime = PubClass.MinDate();
                data.ApplyNumber = "";
                //重新更新申请序号
                updateApplyNumber(applyEntity, keyValue);
            }
            else
            {
                if(data.LastUpdateTime == PubClass.MinDate())
                {
                    data.LastUpdateTime = DateTime.Now;
                    //重新更新申请序号
                    string applyNumber = updateApplyNumber(applyEntity, keyValue);
                    data.ApplyNumber = applyNumber;
                }
            }
            //更新数据
            applyApp.SubmitForm(data, keyValue);
            return Success("操作成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize(ignore: false)]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            ApplyEntity applyEntity = applyApp.GetForm(keyValue);
            //重新更新申请序号
            string applyNumber = updateApplyNumber(applyEntity, keyValue);
            applyApp.Del(keyValue);
            return Success("删除成功。");
        }

        [HttpPost]
        public ActionResult SavePicture(HttpPostedFileBase MyFile, string newFileName)
        {
            //得到的名字是文件在本地机器的绝对路径
            var strLocalFullPathName = MyFile.FileName;
            //定义服务器的文件夹，用来保存文件
            var strServerFilePath = Server.MapPath("/upload/Images/");
            //将接收到文件保存在服务器指定路径下
            var absFilepath = Path.Combine(strServerFilePath, newFileName);
            MyFile.SaveAs(absFilepath);
            return View();
        }

        //取得可申请学位的学校列表
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetEnableSchoolSelectJson(string houseFlag, string classValue)
        {
            var data = schoolApp.GetEnableSchoolList(classValue).OrderBy(t => t.SortId).ToList();
            if ("4" == houseFlag || "5" == houseFlag)
            {
                data = data.Where(t => t.isRent == true).ToList();
            }
            List<object> list = new List<object>();
            list.Add(new { id = "", text = "请选择学校" });
            foreach (SchoolEntity item in data)
            {
                var tempNumber = item.SortId < 10 ? ("0" + item.SortId) : item.SortId.ToString();
                list.Add(new { id = item.F_Id, text = tempNumber + " " + item.SchoolName });
            }
            return Content(list.ToJson());
        }

        //取得可申请学位的学校关联的年级列表
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetEnableClassSelectJson(string enCode, string schoolId)
        {
            var data = itemsDetailApp.GetEnableClassList(enCode, schoolId);
            List<object> list = new List<object>();
            list.Add(new { id = "", text = "请选择" });
            foreach (ItemsDetailEntity item in data)
            {
                list.Add(new { id = item.F_ItemCode, text = item.F_ItemName });
            }
            return Content(list.ToJson());
        }

        //取得住房大类
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetHouseClass()
        {
            var data = ZFine.Code.EnumHelper.GetEnumListStringValues(typeof(ZFine.Application.Enum.Gas.HouseClass));
            List<object> list = new List<object>();
            list.Add(new { id = "", text = "请选择住房所属大类" });
            foreach (string item in data)
            {
                list.Add(new { id = item, text = item });
            }
            return Content(list.ToJson());
        }

        [HttpGet]
        public ActionResult MultiUpdate(string selId)
        {
            if (!string.IsNullOrEmpty(selId))
            {
                string[] arrId = selId.Split(',');
                foreach (var keyValue in arrId)
                {
                    ApplyEntity data = applyApp.GetForm(keyValue);
                    data.OStatus = "5";
                    // 根据住房类别清空div区域字段
                    clearValueByHouseFlag(data);
                    //发送短信通知
                    this.sendSMS(data);
                    //更新数据
                    applyApp.SubmitForm(data, keyValue);
                }
                return Success("操作成功。");
            }
            return Success("操作失败。");
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetReportDataJson(Pagination pagination,string schoolId,string classValue, string ajaxFlag)
        {

            List<SchoolClassEntity> LeftResult = getReportData(schoolId, classValue);

            //单独请求，返回所有结果时
            if ("1" == ajaxFlag)
            {
                var dataAjax = new
                {
                    rows = LeftResult,//全体数据
                };
                return Content(dataAjax.ToJson());
            }

            //记录总数
            pagination.records = LeftResult.ToArray().Length;
            //总页数
            int pageMod = pagination.records % pagination.rows;
            int pageTotal = pagination.records / pagination.rows;
            if (0 != pageMod) pageTotal = pageTotal + 1;
            //当前页的数据
            LeftResult = LeftResult.Skip((pagination.page - 1) * pagination.rows).Take(pagination.rows).ToList();

            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = LeftResult,//分页的数据
                total = pagination.total,//页数
            };
            return Content(data.ToJson());
        }

        private List<SchoolClassEntity> getReportData(string schoolId, string classValue)
        {
            List<ApplyEntity> l_apply = applyApp.GetIQueryable("").ToList();
            List<ClassEntity> l_class = classApp.GetIQueryable(schoolId, classValue).ToList();
            List<SchoolEntity> l_school = schoolApp.GetIQueryable("").ToList();

            var l_class_school = from _class in l_class
                                 join _school in l_school
                                 on _class.SchoolId equals _school.F_Id
                                 select new
                                 {
                                     SchoolId = _class.SchoolId,
                                     ClassValue = _class.Class,
                                     ClassFreeTotalAmount = _class.ClassFreeTotalAmount,
                                     isRent = _school.isRent,
                                     SchoolName = _school.SchoolName
                                 };

            var l_group_apply = from _apply in l_apply
                                group _apply by new
                                {
                                    schoolId = _apply.SchoolId,
                                    classValue = _apply.Class
                                }
                                into s
                                select new
                                {
                                    schoolId = s.Select(p => p.SchoolId).First(),
                                    classValue = s.Select(p => p.Class).First(),
                                    NoSumbitAmount = s.Count(p => p.OStatus == "1"),
                                    SumbitAmount = s.Count(p => p.OStatus == "2"),
                                    FirstNoPassAmount = s.Count(p => p.OStatus == "3"),
                                    PreAdmitAmount = s.Count(p => p.OStatus == "4"),
                                    AdmitAmount = s.Count(p => p.OStatus == "5"),
                                    NoAdmitAmount = s.Count(p => p.OStatus == "6"),
                                };

            //将班级学位表和申请表左连接
            var LeftResult = (from _class in l_class_school
                              join _group_apply in l_group_apply.ToList()
                             on new { schoolId = _class.SchoolId, classValue = _class.ClassValue } equals
                             new { schoolId = _group_apply.schoolId, classValue = _group_apply.classValue }
                             into JoinedTable
                              from table in JoinedTable.DefaultIfEmpty()
                              select new SchoolClassEntity
                              {
                                  SchoolId = _class.SchoolId,
                                  ClassValue = _class.ClassValue,
                                  SchoolName = _class.SchoolName,
                                  ClassFreeTotalAmount = _class.ClassFreeTotalAmount,
                                  isRent = _class.isRent,
                                  ClassFreeAmount = Convert.ToInt16(_class.ClassFreeTotalAmount) - (table == null ? 0 : table?.AdmitAmount ?? 0),
                                  NoSumbitAmount = table == null ? 0 : table?.NoSumbitAmount ?? 0,
                                  SumbitAmount = table == null ? 0 : table?.SumbitAmount ?? 0,
                                  FirstNoPassAmount = table == null ? 0 : table?.FirstNoPassAmount ?? 0,
                                  PreAdmitAmount = table == null ? 0 : table?.PreAdmitAmount ?? 0,
                                  AdmitAmount = table == null ? 0 : table?.AdmitAmount ?? 0,
                                  NoAdmitAmount = table == null ? 0 : table?.NoAdmitAmount ?? 0,
                                  TotalAmount = (table == null ? 0 : table?.NoSumbitAmount ?? 0)
                                  + (table == null ? 0 : table?.SumbitAmount ?? 0)
                                  + (table == null ? 0 : table?.FirstNoPassAmount ?? 0)
                                  + (table == null ? 0 : table?.PreAdmitAmount ?? 0)
                                  + (table == null ? 0 : table?.AdmitAmount ?? 0)
                                  + (table == null ? 0 : table?.NoAdmitAmount ?? 0),
                                  ApplyAmount = (table == null ? 0 : table?.SumbitAmount ?? 0)
                                  + (table == null ? 0 : table?.PreAdmitAmount ?? 0)
                                  + (table == null ? 0 : table?.AdmitAmount ?? 0),
                              }).OrderBy(t => t.SchoolId).ThenBy(t => t.ClassValue).ToList();

            return LeftResult;
        }

        //短信发送
        private void sendSMS(ApplyEntity applyEntity)
        {
            if ("3" == applyEntity.OStatus)
            {
                SMSServices.Send(applyEntity.Phone, SMSTemp.Temp2);
            }
            if ("4" == applyEntity.OStatus)
            {
                SMSServices.Send(applyEntity.Phone, SMSTemp.Temp3);
            }
            if ("5" == applyEntity.OStatus)
            {
                //取得学校
                string schoolName = "";
                SchoolEntity schoolEntity = schoolApp.GetForm(applyEntity.SchoolId);
                if (null != schoolEntity)
                {
                    schoolName = schoolEntity.SchoolName;
                }
                //获得年级
                string className = new ItemsDetailApp().GetSelectedClass("Class", applyEntity.Class);
                //获得报到日期（暂时写死）
                string strDate = "开学后一周内";
                string message = string.Format(SMSTemp.Temp4, schoolName, className, strDate);
                SMSServices.Send(applyEntity.Phone, message);
            }
        }

        // 根据住房类别清空div区域字段
        private void clearValueByHouseFlag(ApplyEntity applyEntity)
        {
            if (null != applyEntity)
            {
                if (applyEntity.HouseFlag == "1")
                {
                    applyEntity.A_CertificateName2 = "";
                    applyEntity.A_CertificateIDNumber2 = "";
                    applyEntity.A_CertificateAddress2 = "";
                    applyEntity.Pic_A_Contract = "";
                    applyEntity.Pic_A_Contract1 = "";
                    applyEntity.Pic_A_Contract2 = "";
                    applyEntity.Pic_A_Contract3 = "";
                    applyEntity.Pic_A_Contract4 = "";
                    //applyEntity.A_CertificateAddress3 = "";
                    applyEntity.Pic_A_Receipt = "";
                    applyEntity.C_RentAddress = "";
                    applyEntity.C_RentAddress1 = "";
                    applyEntity.Pic_C_ResidencePermit = "";
                    applyEntity.Pic_C_FemaleResidencePermit = "";
                    applyEntity.Pic_C_RentContract = "";
                    applyEntity.Pic_C_MaleLaborContract_IN = "";
                    applyEntity.Pic_C_FemaleLaborContract_IN = "";
                    applyEntity.Pic_C_MaleLaborContract_OUT = "";
                    applyEntity.Pic_C_FemaleLaborContract_OUT = "";
                }
                if (applyEntity.HouseFlag == "2")
                {
                    applyEntity.A_CertificateName = "";
                    applyEntity.A_CertificateIDNumber = "";
                    applyEntity.A_CertificateAddress = "";
                    applyEntity.Pic_A_Certificate = "";
                    //applyEntity.A_CertificateAddress3 = "";
                    //applyEntity.Pic_A_Receipt = "";
                    applyEntity.C_RentAddress = "";
                    applyEntity.C_RentAddress1 = "";
                    applyEntity.Pic_C_ResidencePermit = "";
                    applyEntity.Pic_C_FemaleResidencePermit = "";
                    applyEntity.Pic_C_RentContract = "";
                    applyEntity.Pic_C_MaleLaborContract_IN = "";
                    applyEntity.Pic_C_FemaleLaborContract_IN = "";
                    applyEntity.Pic_C_MaleLaborContract_OUT = "";
                    applyEntity.Pic_C_FemaleLaborContract_OUT = "";
                }
                //if (applyEntity.HouseFlag == "3")
                //{
                //    applyEntity.A_CertificateName = "";
                //    applyEntity.A_CertificateIDNumber = "";
                //    applyEntity.A_CertificateAddress = "";
                //    applyEntity.Pic_A_Certificate = "";
                //    applyEntity.A_CertificateName2 = "";
                //    applyEntity.A_CertificateIDNumber2 = "";
                //    applyEntity.A_CertificateAddress2 = "";
                //    applyEntity.Pic_A_Contract = "";
                //    applyEntity.C_RentAddress = "";
                //    applyEntity.C_RentAddress1 = "";
                //    applyEntity.Pic_C_ResidencePermit = "";
                //    applyEntity.Pic_C_RentContract = "";
                //}
                if (applyEntity.HouseFlag == "4")
                {
                    applyEntity.A_CertificateName = "";
                    applyEntity.A_CertificateIDNumber = "";
                    applyEntity.A_CertificateAddress = "";
                    applyEntity.Pic_A_Certificate = "";
                    applyEntity.A_CertificateName2 = "";
                    applyEntity.A_CertificateIDNumber2 = "";
                    applyEntity.A_CertificateAddress2 = "";
                    applyEntity.Pic_A_Contract = "";
                    applyEntity.Pic_A_Contract1 = "";
                    applyEntity.Pic_A_Contract2 = "";
                    applyEntity.Pic_A_Contract3 = "";
                    applyEntity.Pic_A_Contract4 = "";
                    //applyEntity.A_CertificateAddress3 = "";
                    applyEntity.Pic_A_Receipt = "";
                    applyEntity.C_RentAddress1 = "";
                    applyEntity.Pic_C_ResidencePermit = "";
                    applyEntity.Pic_C_FemaleResidencePermit = "";
                    applyEntity.Pic_C_MaleLaborContract_OUT = "";
                    applyEntity.Pic_C_FemaleLaborContract_OUT = "";
                }
                if (applyEntity.HouseFlag == "5")
                {
                    applyEntity.A_CertificateName = "";
                    applyEntity.A_CertificateIDNumber = "";
                    applyEntity.A_CertificateAddress = "";
                    applyEntity.Pic_A_Certificate = "";
                    applyEntity.A_CertificateName2 = "";
                    applyEntity.A_CertificateIDNumber2 = "";
                    applyEntity.A_CertificateAddress2 = "";
                    applyEntity.Pic_A_Contract = "";
                    applyEntity.Pic_A_Contract1 = "";
                    applyEntity.Pic_A_Contract2 = "";
                    applyEntity.Pic_A_Contract3 = "";
                    applyEntity.Pic_A_Contract4 = "";
                    //applyEntity.A_CertificateAddress3 = "";
                    applyEntity.Pic_A_Receipt = "";
                    applyEntity.C_RentAddress = "";
                    applyEntity.Pic_C_RentContract = "";
                    applyEntity.Pic_C_MaleLaborContract_IN = "";
                    applyEntity.Pic_C_FemaleLaborContract_IN = "";
                }
            }
        }

        // 加密身份证号，判断密钥申请（特殊申请的情况）
        private bool isPwdKeyApply(ApplyEntity applyEntity)
        {
            string strIDNumber = applyEntity.IDNumber;
            string strPwdKey = applyEntity.pwdKey;
            applyEntity.isPwdKeyApply = "0";
            if (string.IsNullOrEmpty(strPwdKey))
            {
                return false;
            }
            else
            {
                //密钥确认
                string newPwdKey = Md5.md5(strIDNumber, 16).ToLower();
                if (strPwdKey == newPwdKey.Substring(newPwdKey.Length - 6))
                {
                    applyEntity.isPwdKeyApply = "1";
                    return true;
                }
            }
            return false;
        }

        // 国土-根据姓名和身份证号查询是否存在不动产
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult GetHouseExisInfor(string username, string idnumber)
        {
            try
            {
                ShareRemoteData result = DataSharePubClass.GetHouseExisInfor(username, idnumber);
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = result.message, data = result.result }.ToJson());
            }catch(Exception e)
            {
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = "共享平台数据返回异常，请联系管理员", data = "共享平台数据返回异常，请联系管理员" }.ToJson());
            }
            
        }

        // 国土-根据姓名、身份证证号、不动产地址，查询是否存在匹配信息
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult GetAddressExisInfor(string username, string idnumber, string address)
        {
            try
            {
                ShareRemoteData result = getResultByMultiAddress(username, idnumber, address);
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = result.message, data = result.result }.ToJson());
            }catch(Exception e)
            {
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = "共享平台数据返回异常，请联系管理员", data = "共享平台数据返回异常，请联系管理员" }.ToJson());
            }
        }

        // 房管-根据身份证证号查询该人员的商品房合同备案信息
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult GetContractInfor(string idnumber)
        {
            try
            {
                Remote_Contract_Result result = DataSharePubClass.GetContractInfor(idnumber);
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = result.message,data = result.data }.ToJson());
            }catch(Exception e)
            {
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = "共享平台数据返回异常，请联系管理员", data = "共享平台数据返回异常，请联系管理员" }.ToJson());
            }
        }

        // 根据房屋地址的输入情况，需要多次匹配
        private ShareRemoteData getResultByMultiAddress(string username, string idnumber, string address)
        {
            //默认地址
            ShareRemoteData result = DataSharePubClass.GetAddressExisInfor(username, idnumber, address);
            if (result.total != 0) return result;

            //地址中包含英文逗号（两个地址的情况）
            if (address.Contains(","))
            {
                //英文逗号换成中文逗号
                result = DataSharePubClass.GetAddressExisInfor(username, idnumber, address.Replace(",", "，"));
                if (result.total != 0) return result;

                //把前后两个地址前后调换+英文逗号
                string[] arrayAddress = address.Split(',');
                result = DataSharePubClass.GetAddressExisInfor(username, idnumber, arrayAddress[1] + "," + arrayAddress[0]);
                if (result.total != 0) return result;

                //把前后两个地址前后调换+中文逗号
                result = DataSharePubClass.GetAddressExisInfor(username, idnumber, arrayAddress[1] + "，" + arrayAddress[0]);
                if (result.total != 0) return result;
            }
            if (address.Contains("，"))
            {
                //英文逗号换成中文逗号
                result = DataSharePubClass.GetAddressExisInfor(username, idnumber, address.Replace("，", ","));
                if (result.total != 0) return result;

                //把前后两个地址前后调换+英文逗号
                string[] arrayAddress = address.Split('，');
                result = DataSharePubClass.GetAddressExisInfor(username, idnumber, arrayAddress[1] + "," + arrayAddress[0]);
                if (result.total != 0) return result;

                //把前后两个地址前后调换+中文逗号
                result = DataSharePubClass.GetAddressExisInfor(username, idnumber, arrayAddress[1] + "，" + arrayAddress[0]);
                if (result.total != 0) return result;
            }
            return result;
        }

        //根据第三方共享平台接口验证房屋信息
        private bool checkHouseInfo(ApplyEntity applyEntity)
        {
            if(null != applyEntity)
            {
                if("1" == applyEntity.HouseFlag)
                {
                    ShareRemoteData result = getResultByMultiAddress(applyEntity.A_CertificateName, applyEntity.A_CertificateIDNumber, applyEntity.A_CertificateAddress);
                    if(0 != result.total)
                    {
                        return true;
                    }
                }
                if ("2" == applyEntity.HouseFlag)
                {
                    Remote_Contract_Result result = DataSharePubClass.GetContractInfor(applyEntity.A_CertificateIDNumber2);
                    if (0 != result.total)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        // 家长更新或者删除数据以后更新申请序号
        private string updateApplyNumber(ApplyEntity applyEntity, string keyValue)
        {
            string schoolId = applyEntity.SchoolId;
            string classValue = applyEntity.Class;
            string fId = applyEntity.F_Id;
            List<ApplyEntity> l_apply = applyApp.GetApplyNumberList(schoolId, classValue).Where(t=>t.LastUpdateTime > PubClass.MinDate()).ToList();
            if (!string.IsNullOrEmpty(fId))
            {
                l_apply = l_apply.Where(t => t.F_Id != fId).ToList();
            }
            if (!string.IsNullOrEmpty(keyValue))
            {
                l_apply = l_apply.Where(t => t.F_Id != keyValue).ToList();
            }
            for (int i=1;i<=l_apply.Count;i++)
            {
                l_apply[i - 1].ApplyNumber = i.ToString();
                applyApp.SubmitForm(l_apply[i - 1], l_apply[i - 1].F_Id); 
            }
            return (l_apply.Count + 1).ToString() ;
        }

        // 02.22教体局要求页面
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetReportDataJsonByEducation(Pagination pagination, string schoolId, string classValue)
        {
            List<ApplyEntity> l_apply = applyApp.GetIQueryable("").ToList();
            List<ClassEntity> l_class = classApp.GetIQueryable(schoolId, classValue).ToList();
            List<SchoolEntity> l_school = schoolApp.GetIQueryable("").OrderBy(t=>t.SortId).ToList();

            var l_class_school = from _class in l_class
                                 join _school in l_school
                                 on _class.SchoolId equals _school.F_Id
                                 select new
                                 {
                                     SchoolId = _class.SchoolId,
                                     ClassValue = _class.Class,
                                     ClassFreeTotalAmount = _class.ClassFreeTotalAmount,
                                     isRent = _school.isRent,
                                     SortId = _school.SortId,
                                     SchoolType = _school.SchoolType,
                                 };

            var l_group_apply = from _apply in l_apply
                                group _apply by new
                                {
                                    schoolId = _apply.SchoolId,
                                    classValue = _apply.Class
                                }
                                into s
                                select new
                                {
                                    schoolId = s.Select(p => p.SchoolId).First(),
                                    classValue = s.Select(p => p.Class).First(),
                                    NoSumbitAmount = s.Count(p => p.OStatus == "1"),
                                    SumbitAmount = s.Count(p => p.OStatus == "2"),
                                    FirstNoPassAmount = s.Count(p => p.OStatus == "3"),
                                    PreAdmitAmount = s.Count(p => p.OStatus == "4"),
                                    AdmitAmount = s.Count(p => p.OStatus == "5"),
                                    NoAdmitAmount = s.Count(p => p.OStatus == "6"),
                                };

            //将班级学位表和申请表左连接
            var LeftResult = (from _class in l_class_school
                              join _group_apply in l_group_apply.ToList()
                             on new { schoolId = _class.SchoolId, classValue = _class.ClassValue } equals
                             new { schoolId = _group_apply.schoolId, classValue = _group_apply.classValue }
                             into JoinedTable
                              from table in JoinedTable.DefaultIfEmpty()
                              select new
                              {
                                  SchoolId = _class.SchoolId,
                                  ClassValue = _class.ClassValue,
                                  ClassFreeTotalAmount = _class.ClassFreeTotalAmount,
                                  isRent = _class.isRent,
                                  SortId = _class.SortId,
                                  SchoolType = _class.SchoolType,
                                  ClassFreeAmount = (Convert.ToInt16(_class.ClassFreeTotalAmount) 
                                                            - (table == null ? 0 : table?.AdmitAmount ?? 0) 
                                                            - (table == null ? 0 : table?.PreAdmitAmount ?? 0)).ToString(),
                              }).ToList();

            // 按年级统计数据
            var schoolIdList = LeftResult.Select(p => p.SchoolId).Distinct().ToList();
            List<SchoolSotrEntity> newList = new List<SchoolSotrEntity>();
            for (int i = 0; i < schoolIdList.Count; i++)
            {
                SchoolSotrEntity schoolSotrEntity = new SchoolSotrEntity();
                schoolSotrEntity.SchoolId = schoolIdList[i];
                schoolSotrEntity.classOne = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "1").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "1").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classTwo = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "2").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "2").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classThree = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "3").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "3").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classFour = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "4").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "4").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classFive = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "5").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "5").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classSix = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "6").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "6").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classSeven = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "7").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "7").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classEight = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "8").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "8").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.classNine = LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "9").Select(t => t.ClassFreeAmount).ToList().Count > 0 ? LeftResult.Where(p => p.SchoolId == schoolIdList[i] && p.ClassValue == "9").Select(t => t.ClassFreeAmount).ToList()[0] : "0";
                schoolSotrEntity.isRent = LeftResult.Where(p => p.SchoolId == schoolIdList[i]).Select(t => t.isRent).ToList()[0];
                schoolSotrEntity.SortId = Convert.ToInt16(LeftResult.Where(p => p.SchoolId == schoolIdList[i]).Select(t => t.SortId).ToList()[0]);
                schoolSotrEntity.SchoolType = Convert.ToInt16(LeftResult.Where(p => p.SchoolId == schoolIdList[i]).Select(t => t.SchoolType).ToList()[0]);
                newList.Add(schoolSotrEntity);
            }
            var data = newList.OrderBy(t => t.SortId).ToList();

            pagination.sord = "asc";
            pagination.sidx = "SortId";
            pagination.records = data.Count;
            return ResultDataGrid(pagination.records, data);
        }

        // <summary>
        /// 导出统计报表
        /// </summary>
        public FileResult ExportReportInfo(string schoolId, string classValue)
        {
            List<SchoolClassEntity> rows = getReportData(schoolId, classValue);

            //创建Excel文件的对象  
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("统计报表");
            //给sheet1添加第一行的头部标题  
            NPOI.SS.UserModel.IRow row2 = sheet1.CreateRow(1);
            ICellStyle headStyle = book.CreateCellStyle();
            headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            headStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.FillPattern = FillPattern.SolidForeground;
            IFont font1 = book.CreateFont();
            font1.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
            font1.FontHeightInPoints = 12;
            headStyle.SetFont(font1);
            headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
            headStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
            sheet1.SetColumnWidth(0, 10 * 256);
            sheet1.SetColumnWidth(1, 25 * 256);
            sheet1.SetColumnWidth(2, 25 * 256);
            sheet1.SetColumnWidth(3, 12 * 256);
            sheet1.SetColumnWidth(4, 15 * 256);
            sheet1.SetColumnWidth(5, 10 * 256);
            sheet1.SetColumnWidth(6, 10 * 256);
            sheet1.SetColumnWidth(7, 10 * 256);
            sheet1.SetColumnWidth(8, 10 * 256);
            sheet1.SetColumnWidth(9, 10 * 256);
            sheet1.SetColumnWidth(10, 10 * 256);
            sheet1.SetColumnWidth(11, 10 * 256);

            IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(1).SetCellValue("学校");
            row1.CreateCell(2).SetCellValue("年级");
            row1.CreateCell(3).SetCellValue("年级学位总数");
            row1.CreateCell(4).SetCellValue("年级剩余学位数");
            row1.CreateCell(5).SetCellValue("未提交");
            row1.CreateCell(6).SetCellValue("提交待初审");
            row1.CreateCell(7).SetCellValue("初审未通过");
            row1.CreateCell(8).SetCellValue("预录取");
            row1.CreateCell(9).SetCellValue("录取");
            row1.CreateCell(10).SetCellValue("未录取");
            row1.CreateCell(11).SetCellValue("录取合计");

            int hj_ClassFreeTotalAmount = 0;
            int hj_ClassFreeAmount = 0;
            int hj_NoSumbitAmount = 0;
            int hj_SumbitAmount = 0;
            int hj_FirstNoPassAmount = 0;
            int hj_PreAdmitAmount = 0;
            int hj_AdmitAmount = 0;
            int hj_NoAdmitAmount = 0;
            int hj_TotalAmount = 0;

            for (int i = 0; i < rows.Count; i++)
            {
                IRow row = sheet1.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(Convert.ToString(i + 1));
                row.CreateCell(1).SetCellValue(rows[i].SchoolName);
                row.CreateCell(2).SetCellValue(string.IsNullOrEmpty(rows[i].ClassValue)?"": itemsDetailApp.GetSelectedClass("Class", rows[i].ClassValue));
                row.CreateCell(3).SetCellValue(int.Parse(rows[i].ClassFreeTotalAmount));
                row.CreateCell(4).SetCellValue(rows[i].ClassFreeAmount);
                row.CreateCell(5).SetCellValue(rows[i].NoSumbitAmount);
                row.CreateCell(6).SetCellValue(rows[i].SumbitAmount);
                row.CreateCell(7).SetCellValue(rows[i].FirstNoPassAmount);
                row.CreateCell(8).SetCellValue(rows[i].PreAdmitAmount);
                row.CreateCell(9).SetCellValue(rows[i].AdmitAmount);
                row.CreateCell(10).SetCellValue(rows[i].NoAdmitAmount);
                row.CreateCell(11).SetCellValue(rows[i].TotalAmount);

                hj_ClassFreeTotalAmount += int.Parse(rows[i].ClassFreeTotalAmount);
                hj_ClassFreeAmount += rows[i].ClassFreeAmount;
                hj_NoSumbitAmount += rows[i].NoSumbitAmount;
                hj_SumbitAmount += rows[i].SumbitAmount;
                hj_FirstNoPassAmount += rows[i].FirstNoPassAmount;
                hj_PreAdmitAmount += rows[i].PreAdmitAmount;
                hj_AdmitAmount += rows[i].AdmitAmount;
                hj_NoAdmitAmount += rows[i].NoAdmitAmount;
                hj_TotalAmount += rows[i].TotalAmount;
            }
            IRow rowEnd = sheet1.CreateRow(rows.Count + 1);
            rowEnd.CreateCell(0).SetCellValue("合计");
            rowEnd.CreateCell(3).SetCellValue(hj_ClassFreeTotalAmount);
            rowEnd.CreateCell(4).SetCellValue(hj_ClassFreeAmount);
            rowEnd.CreateCell(5).SetCellValue(hj_NoSumbitAmount);
            rowEnd.CreateCell(6).SetCellValue(hj_SumbitAmount);
            rowEnd.CreateCell(7).SetCellValue(hj_FirstNoPassAmount);
            rowEnd.CreateCell(8).SetCellValue(hj_PreAdmitAmount);
            rowEnd.CreateCell(9).SetCellValue(hj_AdmitAmount);
            rowEnd.CreateCell(10).SetCellValue(hj_NoAdmitAmount);
            rowEnd.CreateCell(11).SetCellValue(hj_TotalAmount);

            string strdate = DateTime.Now.ToString("yyyyMMddHHmmss");//获取当前时间  
            // 写入到客户端   
            MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms -excel", "统计报表" + strdate + ".xls");
        }

        // <summary>
        /// 导出报名结果
        /// </summary>
        public FileResult ExportApplyInfo(string schoolId, string RName, string IDNumber, string OStatus, string txtHouseFlag, string admit, string HouseClass, string IsPwdKeyApply, string classValue)
        {
            List<ApplyEntity> rows = applyApp.GetListByEduForReport(schoolId, RName, IDNumber, OStatus, txtHouseFlag, admit, HouseClass, IsPwdKeyApply, classValue);

            //创建Excel文件的对象  
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("报名查询结果");
            //给sheet1添加第一行的头部标题  
            NPOI.SS.UserModel.IRow row2 = sheet1.CreateRow(1);
            ICellStyle headStyle = book.CreateCellStyle();
            headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            headStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.FillPattern = FillPattern.SolidForeground;
            IFont font1 = book.CreateFont();
            font1.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
            font1.FontHeightInPoints = 12;
            headStyle.SetFont(font1);
            headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
            headStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
            sheet1.SetColumnWidth(0, 10 * 256);
            sheet1.SetColumnWidth(1, 10 * 256);
            sheet1.SetColumnWidth(2, 12 * 256);
            sheet1.SetColumnWidth(3, 12 * 256);
            sheet1.SetColumnWidth(4, 25 * 256);
            sheet1.SetColumnWidth(5, 10 * 256);
            sheet1.SetColumnWidth(6, 10 * 256);
            sheet1.SetColumnWidth(7, 10 * 256);
            sheet1.SetColumnWidth(8, 25 * 256);
            sheet1.SetColumnWidth(9, 25 * 256);
            sheet1.SetColumnWidth(10, 13 * 256);
            sheet1.SetColumnWidth(11, 20 * 256);
            sheet1.SetColumnWidth(12, 20 * 256);
            sheet1.SetColumnWidth(13, 12 * 256);
            sheet1.SetColumnWidth(14, 30 * 256);
            sheet1.SetColumnWidth(15, 30 * 256);
            sheet1.SetColumnWidth(16, 30 * 256);
            sheet1.SetColumnWidth(17, 30 * 256);

            IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(1).SetCellValue("排位号");
            row1.CreateCell(2).SetCellValue("手机号");
            row1.CreateCell(3).SetCellValue("学生姓名");
            row1.CreateCell(4).SetCellValue("第一志愿学校");
            row1.CreateCell(5).SetCellValue("年级");
            row1.CreateCell(6).SetCellValue("状态");
            row1.CreateCell(7).SetCellValue("提交方式");
            row1.CreateCell(8).SetCellValue("学生原所在学校全称");
            row1.CreateCell(9).SetCellValue("第二志愿学校");
            row1.CreateCell(10).SetCellValue("学生家庭情况");
            row1.CreateCell(11).SetCellValue("学生身份证号");
            row1.CreateCell(12).SetCellValue("住房类型");
            row1.CreateCell(13).SetCellValue("住房所属大类");
            row1.CreateCell(14).SetCellValue("A_1_房证上登记地址");
            row1.CreateCell(15).SetCellValue("A_2_购房合同登记地址");
            row1.CreateCell(16).SetCellValue("B_1_租房地址");
            row1.CreateCell(17).SetCellValue("B_2_现居住地址");

            for (int i = 0; i < rows.Count; i++)
            {
                IRow row = sheet1.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(Convert.ToString(i + 1));
                row.CreateCell(1).SetCellValue(rows[i].ApplyNumber);
                row.CreateCell(2).SetCellValue(rows[i].Phone);
                row.CreateCell(3).SetCellValue(rows[i].StudentName);
                row.CreateCell(4).SetCellValue(schoolApp.GetForm(rows[i].SchoolId) == null?"": (string.IsNullOrEmpty(schoolApp.GetForm(rows[i].SchoolId).SchoolName)?"": schoolApp.GetForm(rows[i].SchoolId).SchoolName));
                row.CreateCell(5).SetCellValue(string.IsNullOrEmpty(rows[i].Class) ? "" : itemsDetailApp.GetSelectedClass("Class", rows[i].Class));
                row.CreateCell(6).SetCellValue(getApplyStatus(rows[i].OStatus));
                row.CreateCell(7).SetCellValue(("1" == rows[i].isPwdKeyApply) ? "验证码提交" : "正常提交");
                row.CreateCell(8).SetCellValue(rows[i].OriginalSchool);
                row.CreateCell(9).SetCellValue(schoolApp.GetForm(rows[i].SecondSchoolId) == null ? "" : (string.IsNullOrEmpty(schoolApp.GetForm(rows[i].SecondSchoolId).SchoolName) ? "" : schoolApp.GetForm(rows[i].SecondSchoolId).SchoolName));
                row.CreateCell(10).SetCellValue(string.IsNullOrEmpty(rows[i].FamilySituation) ? "" : itemsDetailApp.GetSelectedClass("FamilySituation", rows[i].FamilySituation));
                row.CreateCell(11).SetCellValue(rows[i].IDNumber);
                row.CreateCell(12).SetCellValue(string.IsNullOrEmpty(rows[i].HouseFlag) ? "" : itemsDetailApp.GetSelectedClass("HouseFlag", rows[i].HouseFlag));
                row.CreateCell(13).SetCellValue(rows[i].HouseClass);
                row.CreateCell(14).SetCellValue(rows[i].A_CertificateAddress);
                row.CreateCell(15).SetCellValue(rows[i].A_CertificateAddress2);
                row.CreateCell(16).SetCellValue(rows[i].C_RentAddress);
                row.CreateCell(17).SetCellValue(rows[i].C_RentAddress1);
            }

            string strdate = DateTime.Now.ToString("yyyyMMddHHmmss");//获取当前时间  
            // 写入到客户端   
            MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms -excel", "报名查询结果" + strdate + ".xls");
        }

        private string getApplyStatus(string ostatus)
        {
            string strStatus = "";
            if (string.IsNullOrEmpty(ostatus))
            {
                return strStatus;
            }
            if (!string.IsNullOrEmpty(ostatus))
            {
                strStatus = itemsDetailApp.GetSelectedClass("schoolOStatus", ostatus);
            }
            if (string.IsNullOrEmpty(strStatus))
            {
                strStatus = itemsDetailApp.GetSelectedClass("studentOStatus", ostatus);
            }
            if (string.IsNullOrEmpty(strStatus))
            {
                strStatus = itemsDetailApp.GetSelectedClass("eduOStatus", ostatus);
            }
            return strStatus;
        }
    }
}
